package com.crm.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.crm.annotation.SystemServiceLog;
import com.crm.model.SysDepartment;
import com.crm.model.SysUser;
import com.crm.model.entity.Tree;
import com.crm.service.SysDepartmentService;
import com.crm.service.SysUserService;
import com.crm.util.AopConfig;
import com.crm.util.CSVUtil;
import com.crm.util.ExcelUtil;
import com.crm.util.FdfsUtil;
import com.crm.util.JsonUtil;
import com.crm.util.PropertyReaderUtil;
import com.crm.util.ResponseUtil;
import com.crm.util.SessionModel;
import com.crm.util.SessionUtils;
import com.crm.util.UUIDUtil;
import com.crm.util.ValidateUtil;
import com.github.pagehelper.Page;
import com.lowagie.text.DocumentException;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/user")
public class SysUserController { 
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysDepartmentService sysDepartmentService;
	 /**  
	 * index:(用户列表). <br/>  
	 *  
	 * @author hanlinxiu  
	 * @param map
	 * @return  
	 * @since JDK 1.8  
	 */
	@RequestMapping("/index")
	public String index(Page<SysUser> page, ModelMap map){
		return "sysconf/user";
	}
	
	/**
	 * 
	* @Description: 加载数据  
	* @author zealot
	* @param @param response
	* @param @param request
	* @param @param pager 
	* @return void    
	* @version 创建时间：2016年10月31日 下午5:23:48  
	* @throws
	 */
	@RequestMapping("/load")
	public void load(Page<SysUser> page, SysUser sysUser,HttpServletResponse response,HttpServletRequest request){
		Page<SysUser> list = (Page<SysUser>) sysUserService.selectAll(page, sysUser);
		ResponseUtil.resultPage(response,request,list);
	}
	 /**
	  * 
	  * @Description : 添加页面解析
	  * @author zealot
	  * @param @return
	  * @return String
	  * @version 创建时间 : 2016年11月1日 下午4:15:49
	  * @thorws
	  */
	@RequestMapping("/toAdd")
	public String toAdd(){
		return "sysconf/user_add_first";
	}
	
	/**
	 * 
	 * @Description : 编辑页面跳转
	 * @author zealot
	 * @param @return
	 * @return String
	 * @version 创建时间 : 2016年11月10日 下午2:31:37
	 * @thorws
	 */
	@SystemServiceLog(description=AopConfig.USER+AopConfig.EDIT+AopConfig.TO,type=AopConfig.EDIT)
	@RequestMapping("/toEditUser/{userId}")
	public String toEditUser(HttpServletRequest request,@PathVariable("userId")String userId){
		SysUser user = sysUserService.selectByPrimaryKey(userId);
		request.setAttribute("user", user);
		request.setAttribute("jobChange", JSONArray.fromObject(user.getJobChange()));
		request.setAttribute("merchantsBankCard",JSONArray.fromObject(user.getMerchantsBankCard()));
		request.setAttribute("eduBackground", JSONArray.fromObject(user.getEduBackground()));
		request.setAttribute("workHistory", JSONArray.fromObject(user.getWorkHistory()));
		return "sysconf/user_edituser";
	}
	 /**  
	 * addNewUser:(插入新用户). <br/>  
	 *  
	 * @author hanlinxiu  
	 * @param user
	 * @return  
	 * @since JDK 1.8  
	 */
	@SystemServiceLog(description=AopConfig.USER+AopConfig.ADD+AopConfig.TO,type=AopConfig.ADD)
	@RequestMapping("/addNewUser")
	@ResponseBody
	public Map<String, Object> addNewUser(SysUser user){
		Map<String, Object> map = new HashMap<>();
		
		List<SysUser> list =  sysUserService.selectByUs(user);
		
		if(list!=null){
			if(list.size()!=0){
				map.put("status", "error");
				map.put("msg", "用户已存在");
				return map;
			}
		}
		
		
		
		if(ValidateUtil.isEmpty(user.getAccount()))
			throw new RuntimeException("用户名不能为空！");
		
		if(ValidateUtil.isEmpty(user.getPassword()))
			throw new RuntimeException("密码不能为空！");
		
		sysUserService.insert(user);
		
		map.put("status", "success");
		map.put("msg", user.getUserId());
		
		return map;
	}
	
	@SystemServiceLog(description=AopConfig.USER+AopConfig.DEL+AopConfig.TO,type=AopConfig.DEL)
	@RequestMapping("/deleteRecord")
	@ResponseBody
	public Map<String, Object> deleteRecord(SysUser record){
		
		Map<String, Object> map = new HashMap<>();
		
		record.setDeleteMark(0);
		sysUserService.updateByPrimaryKey(record);
		
		map.put("status", "success");
		map.put("msg", "删除成功！");
		
		return map;
	}
	
	@SystemServiceLog(description=AopConfig.USER+AopConfig.UPDATE+AopConfig.TO,type=AopConfig.UPDATE)
	@RequestMapping("/updateRecord")
	@ResponseBody
	public Map<String, Object> updateRecord(SysUser record){
		
		Map<String, Object> map = new HashMap<>();
		
		sysUserService.updateByPrimaryKey(record);
		
		map.put("status", "success");
		map.put("msg", "修改成功！");
		
		return map;
	}
	
	/**
	 * 
	 * @Description : 异步获取树形结构
	 * @author zealot
	 * @param @param response
	 * @return void
	 * @version 创建时间 : 2016年11月3日 下午5:49:46
	 * @thorws
	 */
	@RequestMapping("/ajaxLoadTree")
	public void ajaxLoadTree(HttpServletResponse response,Tree tree){
		List<Tree> list = sysDepartmentService.selectMasterByParm(tree);
		ResponseUtil.result(response, JsonUtil.toJsonStr(list));
	}
	@RequestMapping("/ajaxLoadDepartmentTree")
	public void ajaxLoadDepartmentTree(HttpServletResponse response,Tree tree){
		List<Tree> list = sysDepartmentService.selectByParm(tree);
		ResponseUtil.result(response, JsonUtil.toJsonStr(list));
	}
	
	/**
	 * 
	 * @Description : 联动树形结构
	 * @author zealot
	 * @param @param response
	 * @param @param tree
	 * @return void
	 * @version 创建时间 : 2016年11月21日 下午5:57:43
	 * @thorws
	 */
	@RequestMapping("/ajaxLoadMaterTree")
	public void ajaxLoadMaterTree(HttpServletResponse response,Tree tree){
		List<Tree> list = sysDepartmentService.selectMaster();
		ResponseUtil.result(response, JsonUtil.toJsonStr(list));
	}
	
	/**
	 * 
	 * @Description : 获取公司
	 * @author zealot
	 * @param @param response
	 * @return void
	 * @version 创建时间 : 2016年11月3日 下午2:52:08
	 * @thorws
	 */
	@RequestMapping("/ajaxLoadCompny")
	public void ajaxLoadCompny(HttpServletResponse response){
		SysDepartment sd = new SysDepartment();
		sd.setParentId("0");
		List<SysDepartment> list = sysDepartmentService.selectByUs(sd);
		ResponseUtil.result(response, JsonUtil.toJsonStr(list));
	}
	
	/**
	 * 
	 * @Description : 获取部门
	 * @author zealot
	 * @param @param response
	 * @param @param sysDepartment
	 * @return void
	 * @version 创建时间 : 2016年11月3日 下午2:52:22
	 * @thorws
	 */
	@RequestMapping("/ajaxLoadDepartment")
	public void ajaxLoadDepartment(HttpServletResponse response,SysDepartment sysDepartment){
		List<SysDepartment> list = sysDepartmentService.selectByUs(sysDepartment);
		ResponseUtil.result(response, JsonUtil.toJsonStr(list));
	}
	
	/**
	 * 
	 * @Description : 用户导出excel
	 * @author zealot
	 * @param @param response
	 * @param @throws IOException
	 * @return void
	 * @version 创建时间 : 2016年11月15日 上午9:56:05
	 * @thorws
	 */
	@RequestMapping("/downloadExcel")
	public void downloadExcel(HttpServletResponse response) throws IOException{
		List<SysUser> list = sysUserService.selectByUs(null);
		HSSFWorkbook wb =  ExcelUtil.productExcel(list,SysUser.class);
		ResponseUtil.downloadExcel(wb, response, "11");
		
	}
	
	/**
	 * 
	 * @Description : 用户导出CSV
	 * @author zealot
	 * @param @param response
	 * @param @throws IOException
	 * @return void
	 * @version 创建时间 : 2016年11月16日 上午10:25:55
	 * @throws InstantiationException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @thorws
	 */
	@RequestMapping("/downloadCSV")
	public void downloadCSV(HttpServletResponse response) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException{
		List<SysUser> list = sysUserService.selectByUs(null);
		byte[] buff =  CSVUtil.export(CSVUtil.reflectValueList(new SysUser(),list));
		ResponseUtil.downloadCSV(buff, response, "11");
	}
	
	/**
	 * 
	 * @Description : pdf导出
	 * @author zealot
	 * @param @param response
	 * @param @throws IOException
	 * @param @throws SecurityException
	 * @param @throws NoSuchMethodException
	 * @param @throws IllegalArgumentException
	 * @param @throws IllegalAccessException
	 * @param @throws InvocationTargetException
	 * @param @throws InstantiationException
	 * @param @throws DocumentException
	 * @return void
	 * @version 创建时间 : 2016年11月16日 下午6:25:29
	 * @thorws
	 */
	@RequestMapping("/downloadPDF")
	public void downloadPDF(HttpServletResponse response) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, DocumentException{
		List<SysUser> list = sysUserService.selectByUs(null);
		ResponseUtil.downloadPDF(list, response, "11",SysUser.class);
	}
	
	@RequestMapping("/selectByUserId")
	@ResponseBody
	public Map<String, Object> selectByUserId(Page<SysUser> page, SysUser record){
		Map<String, Object> map = new HashMap<>();
		Page<SysUser> list = (Page<SysUser>)sysUserService.selectByUserId(page, record);
		map.put("list", list);
		map.put("status", "success");
		map.put("msg", "获取成功！");	
		return map;
	}
	
	@RequestMapping("/selectByDepartmentUserId")
	@ResponseBody
	public Map<String, Object> selectByDepartmentUserId(Page<SysUser> page, SysUser record){
		Map<String, Object> map = new HashMap<>();
		Page<SysUser> list = (Page<SysUser>)sysUserService.selectByDepartmentUserId(page, record);
		map.put("list", list);
		map.put("status", "success");
		map.put("msg", "获取成功！");	
		return map;
	}
	
	@RequestMapping("/selectUserByDutyId")
	@ResponseBody
	public Map<String, Object> selectUserByDutyId(Page<SysUser> page,SysUser record){
		Map<String, Object> map = new HashMap<>();
		Page<SysUser> list =(Page<SysUser>) sysUserService.selectUserByDutyId( page, record);
		map.put("list", list);
		map.put("status", "success");
		map.put("msg", "获取成功！");	
		return map;
	}
	@RequestMapping("/changeHeadImage")
	@ResponseBody
	public Map<String, Object> changeHeadImage(HttpServletRequest request,
			@RequestParam("avatar_file") MultipartFile uploadFile, String avatar_data) throws Exception{
		Map<String,Object> retMap = new HashMap<>();
		long limitSize= 2*1024*1024;
		long fileSize = uploadFile.getSize();
		if(fileSize>limitSize){
			retMap.put("msg", "文件大小超过限制");
			return retMap;
		}
		String originalFileName = uploadFile.getOriginalFilename();
		String fileExt = originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase();
	    Map<String, Object> dataMap = JsonUtil.toMap(avatar_data);
	    BufferedImage img = ImageIO.read(uploadFile.getInputStream());
	   
	    int x = Double.valueOf(String.valueOf(dataMap.get("x"))).intValue();
	    int y = Double.valueOf(String.valueOf(dataMap.get("y"))).intValue();
	    int width = Double.valueOf(String.valueOf(dataMap.get("width"))).intValue();
	    int height = Double.valueOf(String.valueOf(dataMap.get("height"))).intValue();
	    if(x<0||y<0){
	    	retMap.put("msg", "在图像框内截取");
			return retMap;
	    }
	    img = img.getSubimage(x, y, width, height);
	    ByteArrayOutputStream bos = new ByteArrayOutputStream();
	    ImageIO.write(img, fileExt, bos);
		
		String files[] = {};
		files = FdfsUtil.uploadFile(bos.toByteArray(), originalFileName,fileExt,fileSize);
		if(!ValidateUtil.isEmpty(files)){
			SysUser sy =  (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
			sy.setAvatar(files[0] + "/" + files[1]);
			sysUserService.updateHeadImage(sy);
			retMap.put("error", 0);
			retMap.put("url", PropertyReaderUtil.getValue("/config.properties", "fdfs_host") + files[0] + "/" + files[1]);
			return retMap;
		}else{
			retMap.put("msg", "上传错误！");
		}
		return retMap;
	}
	@RequestMapping("/changePwd")
	@ResponseBody
	public Map<String, Object> changePwd(HttpServletRequest request,
			@RequestParam(value="userId",required=false)String userId,
			@RequestParam(value="oldPassword",required=false)String oldPassword,
			String newPassword) throws Exception{
		Map<String,Object> retMap = new HashMap<>();
		SysUser user = new SysUser();
		if(StringUtils.isNotBlank(userId)){
			user.setUserId(userId);
		}else{
			SysUser sy =  (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
			oldPassword = UUIDUtil.getMD5(oldPassword, sy.getUserId());
			String userPwd = sy.getPassword();
			if(!userPwd.equals(oldPassword)){
				retMap.put("msg", "原始密码不正确");
				return retMap;
			}
			user.setUserId(sy.getUserId());
		}
		user.setPassword(UUIDUtil.getMD5(newPassword,user.getUserId()));
		sysUserService.changePassword(user.getUserId(), user.getPassword());
		retMap.put("error", 0);
		return retMap;
	}
	
	@RequestMapping("/updatePasswordBath")
	@ResponseBody
	public String updatePasswordBath(){
		
		sysUserService.updatePasswordBatch();
		
		return "UPDATE OK";
	}
}
